package org.kafkaliu.app.peddlerstore.domain.dao.impl;

import java.util.List;

import org.kafkaliu.app.peddlerstore.domain.dao.GenericDao;
import org.springframework.orm.jpa.support.JpaDaoSupport;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

public class GenericDaoImpl<T> extends JpaDaoSupport implements GenericDao<T> {

	@SuppressWarnings("unchecked")
	@Transactional(readOnly = true)
	public T find(Class<T> clazz, Long id) {
		List<T> result = this.getJpaTemplate().find("select p from " + clazz.getName() + " p.id =" + id);
		return result.isEmpty() ? null : result.get(0);	}

	@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
	public T save(T obj) {
		return this.getJpaTemplate().merge(obj);
	}

	@SuppressWarnings("unchecked")
	@Transactional(readOnly = true)
	public List<T> findAll(Class<T> clazz) {
		return this.getJpaTemplate().find("select p from " + clazz.getName() + " p");
	}

	@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
	public void delete(T obj) {
		this.getJpaTemplate().remove(obj);
	}

}
